// controllers/userController.js
import User from "../models/User.js";
import { hashPassword, comparePassword } from "../utils/bcrypt.js";
import jwt from "jsonwebtoken";

const SECRET_KEY = "your_secret_key"; // 建议放到 .env 文件
const REFRESH_SECRET_KEY = "your_refresh_secret_key";

// 注册（或初始化）用户
export const createUser = async (req, res) => {
  const { username: name, password } = req.body;
  if (!name || !password) {
    return res.json({ code: 1, msg: "用户名或密码不能为空" });
  }

  // 检查用户名是否已存在
  const existingUser = await User.findOne({ name });
  if (existingUser) {
    return res.json({ code: 1, msg: "用户名已存在" });
  }

  // 密码加密存储
  const hashedPassword = await hashPassword(password);

  // 创建新用户
  const user = await User.create({
    name,
    password: hashedPassword,
    isActive: true, // 默认活跃状态
  });

  res.json({
    code: 0,
    msg: "注册成功",
    data: { name: user.name },
  });
};

// 用户登录
export const loginUser = async (req, res) => {
  const { name, password } = req.body;

  const user = await User.findOne({ name });
  if (!user) return res.json({ code: 1, msg: "用户不存在" });

  const match = await comparePassword(password, user.password);
  if (!match) return res.json({ code: 1, msg: "密码错误" });

  // 1. 生成 Access Token
  const accessToken = jwt.sign(
    { id: user._id, name: user.name },
    SECRET_KEY,
    { expiresIn: "2h" }
  );

  // 2. 生成 Refresh Token
  const refreshToken = jwt.sign(
    { id: user._id, name: user.name },
    REFRESH_SECRET_KEY,
    { expiresIn: "7d" }
  );

  res.json({
    code: 0,
    data: {
      name: user.name,
      accessToken,
      refreshToken,
      userInfo: { name: user.name, role: "admin" },
    },
  });
};

// 刷新 Token 控制器
export const refreshAccessToken = (req, res) => {
  const { refreshToken } = req.body;

  if (!refreshToken) {
    return res.status(401).json({ code: 1, msg: '缺少 refresh token' });
  }

  jwt.verify(refreshToken, REFRESH_SECRET_KEY, (err, decoded) => {
    if (err) return res.status(401).json({ code: 1, msg: 'refresh token 无效' });

    const newAccessToken = jwt.sign(
      { id: decoded.id, name: decoded.name },
      SECRET_KEY,
      { expiresIn: '2h' }
    );

    res.json({ code: 0, data: { accessToken: newAccessToken } });
  });
};
